var app = getApp(), u = app.require("utils/util.js"), a = app.require("utils/api.js"), o = app.require("utils/onfire.js"), h = app.require("utils/http.js"), n = app.require("utils/enums"), 
utilMd5 = app.require('utils/md5.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    order_no:null,
    userInfo:null,
    nowOrder:null,
    userAddress:null,
    proList:[],
    pouponList: [{ coupon_id: 0, cname: '不使用优惠券', face_money:'0.00'}],
    coupon_id:0,
    couponName:'',
    actualTotal: '0.00'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.userInfo = wx.getStorageSync('userInfo');
    this.data.order_no = options.order_no;
  },
  onShow:function(){
    this.getPayInfo();     
  },
  // 获取支付详情
  getPayInfo(){
    var t = this;
    var data = {
      store_id: a.storeId,
      uid: t.data.userInfo.uid,
      order_no: t.data.order_no
    };
    h.postReq(a.toPay, data, function (res) {
      if(res.code == 0){ 
        if (!res.data.userAddress) {
          t.showDialog();
        }else {
          t.hideDialog();
        }
        var pouponList = t.data.pouponList.concat(res.data.userCoupon);
        pouponList = t._addChecked(pouponList);        
        t.setData({
          nowOrder: res.data.nowOrder,
          userAddress: res.data.userAddress,
          proList: res.data.nowOrder.proList,
          actualTotal: res.data.nowOrder.total,
          pouponList: pouponList,
        });        
      }else{
        u.toast(res.message);
      }
    });
  },
  _addChecked: function (pouponList){
    for(let i = 0;i < pouponList.length; i++){
      if(i == 0){
        pouponList[i].checked = true;
        this.setData({ couponName: pouponList[i].cname});
      }else {
        pouponList[i].checked = false;
      }      
    }
    return pouponList;
  },
  // 单选按钮实现 
  changeStatus:function(e){
    console.log(e);
    var t = this;
    var key = e.currentTarget.dataset.key;
    for (let i = 0; i < t.data.pouponList.length; i++) {
      if(i == key){
        t.data.pouponList[i].checked = true;
        t.setData({
          coupon_id: t.data.pouponList[i].coupon_id,
          couponName: t.data.pouponList[i].cname, 
          actualTotal: t.recount(t.data.pouponList[i].face_money)
        });
      }else {
        t.data.pouponList[i].checked = false;
      }
    }
    t.setData({ pouponList: t.data.pouponList});
    t.closeCoupon();//关闭优惠券弹窗
  },
  // 计算出抵用优惠券后的价格
  recount: function (face_money){
    // console.log(face_money);return;
    var t = this;
    var multiple = 100;
    if (face_money == '0.00'){
      return t.data.nowOrder.total;
    }else{
      var account = ((t.data.nowOrder.total) * multiple) - (face_money * multiple);
      account = (account / multiple) < 0 ? '0.00' : (account / multiple);
      // console.log(parseFloat(account));return;
      return parseFloat(account).toFixed(2);
    }    
  },

  toAddress:function(){
    wx.navigateTo({
      url: '/pages/mine/address/index?source=pay',
    })
  },
  // 提示添加收货地址部分
  showDialog() {
    let dialogComponent = this.selectComponent('.wxc-dialog');
    dialogComponent && dialogComponent.show();
  },
  hideDialog() {
    let dialogComponent = this.selectComponent('.wxc-dialog');
    dialogComponent && dialogComponent.hide();
  },
  onConfirm() {
    console.log('点击了确认按钮');
    // this.hideDialog();
    wx.navigateTo({
      url: '/pages/mine/address/index',
    })
  },
  onCancel() {
    console.log('点击了取消按钮');
    wx.navigateBack();
  },
  // 提示添加收货地址部分


  // 优惠券部分
  // 显示优惠券弹窗
  showCoupon:function(e){
    let popupComponent = this.selectComponent('.coupon_popup');
    popupComponent && popupComponent.show();
  },
  // 关闭优惠券弹窗
  closeCoupon: function () {
    let popupComponent = this.selectComponent('.coupon_popup');
    popupComponent && popupComponent.hide();
  },
  //优惠券部分


  // 拉起微信支付
  execPay:function(e){
    var t = this;
    var order_id = t.data.nowOrder.order_id;
    var data = {
      store_id:a.storeId,
      uid: t.data.userInfo.uid,
      order_id: order_id,
      pay_money: t.data.actualTotal
    };
    if (t.data.actualTotal > 0){
      h.noLoadReq(a.execPay, data, 'POST', function (res) {
        if (res.code == 0) {
          var data = res.data;
          var timestamp = Date.parse(new Date());
          timestamp = (timestamp / 1000).toString();
          var signData = {
            appId: data.appid,
            nonceStr: data.nonce_str,
            package: 'prepay_id=' + data.prepay_id,
            timeStamp: timestamp,
            key: data.key
          };
          var paySign = t._generateSign(signData);
          wx.requestPayment({
            'timeStamp': timestamp,
            'nonceStr': data.nonce_str,
            'package': 'prepay_id=' + data.prepay_id,
            'signType': 'MD5',
            'paySign': paySign,
            success: function (res) {
              console.log(res);
              u.success('支付成功', function () {
                t.paySuccess(t.data.actualTotal);
              });
            },
            fail: function (res) {
              console.log(res);
              u.error('支付失败');
            }
          });
        } else {
          u.toast(res.message);
        }
      });
    }else{
      u.success('支付成功', function () {
        t.paySuccess(t.data.actualTotal);
      });
    }

  },
  // 支付成功回调
  paySuccess: function (actualTotal) {
    var t = this;
    var data = {
      order_no: t.data.order_no,
      user_address_id: t.data.userAddress.address_id,
      coupon_id: t.data.coupon_id,
      pay_money: actualTotal,
    };
    h.noLoadReq(a.paySuccess, data, 'POST', function (res) {
      if (res.code == 0) {
        wx.navigateTo({
          url: '/pages/order/my/index?type=unsend',
        });
      } else {
        u.toast(res.message);
      }
    });
  },  
  // 生成支付请求签名
  _generateSign:function(data){
    var payKey = "l3L19WpE2biJbcYwrOmGiR4Ys7tHlFqG";
    var stringA = "appId=" + data.appId + "&nonceStr=" + data.nonceStr + "&package=" + data.package + "&signType=MD5&timeStamp=" + data.timeStamp + "&key=" + payKey;
    var sign = utilMd5.hexMD5(stringA).toUpperCase();
    return sign;
  },

})